package com.qf.first.controller;


import com.qf.first.entity.Food;
import com.qf.first.pojo.vo.RespVo;
import com.qf.first.service.FoodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Api(tags = "餐品模块")
@RestController
@RequestMapping("/food")
public class FoodController extends BaseController {
    @Autowired
    private FoodService foodService;

    @ApiOperation("根据分类id获取所属的餐品信息")
    @GetMapping("/getFoodsByCategoryId")
    public RespVo getCategoriesByShopId(Long categoryId){
        List<Food> foodsList = foodService.findFoodsByCategoryId(categoryId);
        return convertSuccess(foodsList);
    }

    @ApiOperation("添加餐品信息")
    @PostMapping(value = "/addFood",consumes = "multipart/*",headers = "content-type=multipart/form-data")
    public RespVo addFood(Food food, MultipartFile file, HttpServletRequest request){
        //获取文件名
        String fileName = file.getOriginalFilename();
        //文件名拼接UUID
        fileName = UUID.randomUUID().toString()+"_"+fileName;

        String path = request.getSession().getServletContext().getRealPath("imgs");
        File readPath = new File(path);
        if (!readPath.exists()){
            readPath.mkdirs();
        }
        try {
            file.transferTo(new File(readPath+"/"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        food.setFoodUrl(fileName);
        String msg = foodService.addFood(food);
        return convertSuccess(msg);
    }

    @ApiOperation("根据当前id删除该餐品")
    @GetMapping("/deleteFood")
    public RespVo deleteFood(Food food){
        String msg = foodService.deleteFood(food);
        return convertSuccess(msg);
    }

}
